<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 上传相关服务 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\service;


use think\Config;

class UploadService {
    const UPLOAD_DIR_NAME = "uploads";

    /**
     * 附件保存
     *
     * @param \think\File $file
     * @return bool|\think\File $file
     */
    public static function save($file) {
        if (!isset($file) || empty($file)) {
            return false;
        }

        $fileType = "file";
        if (startsWith($file->getInfo('type'), 'image')) {
            $fileType = 'image';
            $file->validate(['size' => self::_getMaxSize($fileType), 'ext' => 'jpg,png,gif,ico,bmp,jpeg']);
        } else {
            $file->validate(['size' => self::_getMaxSize($fileType)]);
        }

        // 移动到框架应用根目录/public/uploads/ 目录下
        $savedFile = $file->move(ROOT_PATH . 'public/' . self::UPLOAD_DIR_NAME . '/' . $fileType);
        if ($savedFile && $savedFile instanceof \think\File) {
            $fileInfo = $savedFile->getInfo();
            $fileInfo['fileUrl'] = '/' . self::UPLOAD_DIR_NAME . '/' . $fileType . '/' . $savedFile->getSaveName();
            $fileInfo['fileUrl'] = str_replace('\\', '/', $fileInfo['fileUrl']);
            $savedFile->setUploadInfo($fileInfo);
        } else {
            return $file->getError();
        }
        return $savedFile;
    }

    /**
     * 获取某种文件类型设置的最大上传文件大小
     *
     * @param $type
     * @return mixed
     */
    private static function _getMaxSize($type) {
        $maxSizeConfig = Config::get("upload.maxsize");
        $maxsize = fetch($maxSizeConfig, $type);
        if (!empty($maxsize)) {
            return $maxsize;
        }
        return fetch($maxSizeConfig, "file", 10485760);
    }
}